package com.lanou.utils;

import com.lanou.bean.AdminInfo;
import com.lanou.mapper.AdminInfoMapper;
import com.lanou.service.AdminServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by lanouhn on 17/10/25.
 */
@WebFilter(filterName = "RightFilter")
public class RightFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取session中的ladminInfo
        AdminInfo adminInfo = (AdminInfo) request.getSession().getAttribute("adminInfo");
        String url = request.getRequestURI();
        //如果不是登录界面，判断是否登录状态
        if (!url.contains("login")) {
            //如果是登录状态，放行
            if (adminInfo == null) {
                //获取浏览器的cookie
                Cookie cookie = CookieUtils.getCookie(request.getCookies(), "autoLogin");
                if (cookie != null) {

                    AdminInfo adminInfo1 = new AdminInfo();
                    adminInfo1.setName(cookie.getValue().split("-")[0]);
                    adminInfo1.setPassword(cookie.getValue().split("-")[1]);
                    request.getSession().setAttribute("adminInfo", adminInfo1);
                } else {
                    request.getSession().setAttribute("masgs", "你还没有登录");
                    response.sendRedirect("/login.jsp");
                }
            }
        }
        //是登陆界面，放行
        chain.doFilter(req, resp);
    }

    public void destroy() {

    }

}
